// 侧边栏主要功能实现
class WebPageSummarizer {
    constructor() {
        this.currentResult = null;
        this.lastSummarizedUrl = null;
        this.init();
        this.listenForPageUrlChange();
        this.setupPortListener();
    }

    init() {
        this.bindEvents();
        this.loadSettings();
        this.loadHistory();
        this.setupAutoSummarizeOnUrlChange();
    }

    setupAutoSummarizeOnUrlChange() {
        this.lastSummarizedUrl = location.href;
        // 监听常见的页面导航和刷新事件
        const trigger = async () => {
            const settings = await this.getSettings();
            if (settings.autoSummarize && location.href !== this.lastSummarizedUrl) {
                this.lastSummarizedUrl = location.href;
                this.summarizeCurrentPage();
            }
        };
        window.addEventListener('popstate', trigger);
        window.addEventListener('hashchange', trigger);
        window.addEventListener('pageshow', trigger);
        document.addEventListener('visibilitychange', () => {
            if (!document.hidden) trigger();
        });
        // 轮询兜底，防止部分跳转事件漏掉
        setInterval(trigger, 1500);
    }

    bindEvents() {
        // 总结按钮
        document.getElementById('summarizeBtn').addEventListener('click', () => {
            this.summarizeCurrentPage();
        });

        // 设置按钮
        document.getElementById('settingsBtn').addEventListener('click', () => {
            this.toggleSettings();
        });

        // 历史按钮
        document.getElementById('historyBtn').addEventListener('click', () => {
            this.toggleHistory();
        });

        // 保存设置
        document.getElementById('saveSettingsBtn').addEventListener('click', () => {
            this.saveSettings();
        });

        // 取消设置
        document.getElementById('cancelSettingsBtn').addEventListener('click', () => {
            this.toggleSettings();
        });

        // 复制总结
        document.getElementById('copyBtn').addEventListener('click', () => {
            this.copySummary();
        });

        // 保存总结
        document.getElementById('saveBtn').addEventListener('click', () => {
            this.saveSummary();
        });

        // 重新生成
        document.getElementById('regenerateBtn').addEventListener('click', () => {
            this.summarizeCurrentPage();
        });

        // 清空历史
        document.getElementById('clearHistoryBtn').addEventListener('click', () => {
            this.clearHistory();
        });

        // 关闭历史
        document.getElementById('closeHistoryBtn').addEventListener('click', () => {
            this.toggleHistory();
        });
    }

    async summarizeCurrentPage() {
        const summarizeBtn = document.getElementById('summarizeBtn');
        const resultArea = document.getElementById('resultArea');

        try {
            // 禁用按钮
            summarizeBtn.disabled = true;
            summarizeBtn.textContent = '⏳ 分析中...';

            // 获取当前页面内容
            const pageContent = await this.getPageContent();
            
            // 调用KIMI API
            const summary = await this.callKimiAPI(pageContent);
            
            // 显示结果
            this.displayResult(summary);
            
            // 保存到历史记录
            this.saveToHistory(summary);

        } catch (error) {
            console.error('总结失败:', error);
            this.showError('总结失败: ' + error.message);
        } finally {
            // 恢复按钮
            summarizeBtn.disabled = false;
            summarizeBtn.textContent = '📝 一键总结当前页面';
        }
    }

    async getPageContent() {
        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

        // 检查是否为有效页面
        if (!tab.id || !tab.url || !tab.url.startsWith('http')) {
            throw new Error('无法在当前页面运行 (例如 chrome:// 或 about:blank 页面)');
        }

        try {
            // 动态注入内容脚本
            await chrome.scripting.executeScript({
                target: { tabId: tab.id },
                files: ['content.js'],
            });

            // 发送消息到内容脚本
            const response = await chrome.tabs.sendMessage(tab.id, { action: 'getPageContent' });
            
            if (response && response.content) {
                return response.content;
            } else {
                throw new Error('未能从页面获取有效内容。');
            }
        } catch (e) {
            console.error('获取页面内容失败:', e);
            // 提供更具体的错误信息
            if (e.message.includes('Receiving end does not exist')) {
                 throw new Error('无法连接到页面。请刷新页面后重试。');
            }
            throw new Error(`获取内容时出错: ${e.message}`);
        }
    }

    async callKimiAPI(pageContent) {
        const settings = await this.getSettings();
        
        if (!settings.apiKey) {
            throw new Error('请先设置API密钥');
        }

        // 检查API密钥格式 - 支持KIMI API (sk-) 和 Moonshot API (ms-)
        if (!settings.apiKey.startsWith('sk-') && !settings.apiKey.startsWith('ms-')) {
            throw new Error('API密钥格式错误，应以"sk-"或"ms-"开头');
        }

        const prompt = `请对以下网页内容进行智能、精炼的总结，要求：
1. **一句话总结**: 用一句话精准概括全文核心主旨，不超过50个字。
2. **关键要点**: 提取几个最关键的要点，每个要点力求简短，最好在20字以内。

网页内容：
${pageContent.substring(0, 8000)} // 限制内容长度

请严格按照以下格式返回，不要有任何多余的文字：
一句话总结：[这里是总结]
关键要点：
• [要点1]
• [要点2]
• [要点3]`;

        // 使用正确的API端点
        const apiUrl = 'https://api.moonshot.cn/v1/chat/completions';

        console.log('发送API请求:', {
            url: apiUrl,
            model: settings.model || 'moonshot-v1-8k',
            apiKeyType: `Key starts with: ${settings.apiKey.substring(0, 3)}`
        });

        // 使用标准的OpenAI请求格式
        const requestBody = {
            model: settings.model || 'moonshot-v1-8k',
            messages: [
                {
                    role: 'user',
                    content: prompt
                }
            ],
            max_tokens: settings.maxTokens || 1000,
            temperature: 0.3
        };

        const response = await fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${settings.apiKey}`
            },
            body: JSON.stringify(requestBody)
        });

        console.log('API响应状态:', response.status);
        
        if (!response.ok) {
            let errorMessage = `HTTP ${response.status}: ${response.statusText}`;
            try {
                const errorText = await response.text();
                console.log('错误响应内容:', errorText);
                const errorData = JSON.parse(errorText);
                errorMessage = errorData.error?.message || errorMessage;
            } catch (e) {
                // 忽略解析错误
            }
            throw new Error(errorMessage);
        }

        const data = await response.json();

        if (!data.choices || !data.choices[0] || !data.choices[0].message) {
            throw new Error('API响应格式异常');
        }
        
        const content = data.choices[0].message.content;
        return this.parseSummary(content);
    }

    parseSummary(content) {
        const summary = {
            mainContent: '',
            keyPoints: [],
        };

        // 解析一句话总结
        const mainContentMatch = content.match(/一句话总结：(.+?)(?=\n关键要点：|$)/s);
        if (mainContentMatch) {
            summary.mainContent = mainContentMatch[1].trim();
        } else {
            // 如果没有找到格式化的内容，尝试使用旧格式或直接使用前几行作为主要内容
            const oldFormatMatch = content.match(/主要内容：(.+?)(?=\n关键要点：|$)/s);
            if (oldFormatMatch) {
                summary.mainContent = oldFormatMatch[1].trim();
            } else {
                summary.mainContent = content.split('\n').slice(0, 3).join(' ').trim();
            }
        }

        // 解析关键要点
        const keyPointsMatch = content.match(/关键要点：\n((?:• .+\n?)+)/);
        if (keyPointsMatch) {
            summary.keyPoints = keyPointsMatch[1]
                .split('\n')
                .filter(line => line.trim().startsWith('•'))
                .map(line => line.replace('• ', '').trim())
                .filter(line => line.length > 0);
        } else {
            // 如果没有找到格式化的要点，尝试提取列表项
            const lines = content.split('\n');
            summary.keyPoints = lines
                .filter(line => line.trim().startsWith('•') || line.trim().startsWith('-'))
                .map(line => line.replace(/^[•\-]\s*/, '').trim())
                .filter(line => line.length > 0)
                .slice(0, 5);
        }

        return summary;
    }

    displayResult(summary) {
        this.currentResult = summary;
        
        // 显示主要内容
        document.getElementById('mainContent').textContent = summary.mainContent;
        
        // 显示关键要点
        const keyPointsElement = document.getElementById('keyPoints');
        keyPointsElement.innerHTML = summary.keyPoints
            .map(point => `<div>• ${point}</div>`)
            .join('');
        
        // 显示结果区域
        document.getElementById('resultArea').style.display = 'block';
        
        // 隐藏其他面板
        this.hideAllPanels();
    }

    toggleSettings() {
        const settingsPanel = document.getElementById('settingsPanel');
        const isVisible = settingsPanel.style.display !== 'none';
        
        if (isVisible) {
            settingsPanel.style.display = 'none';
        } else {
            this.hideAllPanels();
            settingsPanel.style.display = 'block';
        }
    }

    toggleHistory() {
        const historyPanel = document.getElementById('historyPanel');
        const isVisible = historyPanel.style.display !== 'none';
        
        if (isVisible) {
            historyPanel.style.display = 'none';
        } else {
            this.hideAllPanels();
            historyPanel.style.display = 'block';
            this.loadHistory();
        }
    }

    hideAllPanels() {
        document.getElementById('settingsPanel').style.display = 'none';
        document.getElementById('historyPanel').style.display = 'none';
    }

    async saveSettings() {
        const apiKey = document.getElementById('apiKey').value.trim();
        const model = document.getElementById('modelSelect').value;
        const maxTokens = parseInt(document.getElementById('maxTokens').value);
        const autoSummarize = document.getElementById('autoSummarizeSwitch').checked;

        if (!apiKey) {
            this.showError('请输入API密钥');
            return;
        }

        if (!apiKey.startsWith('sk-') && !apiKey.startsWith('ms-')) {
            this.showError('API密钥格式错误，应以"sk-"或"ms-"开头');
            return;
        }

        const settings = {
            apiKey,
            model,
            maxTokens,
            autoSummarize
        };

        await chrome.storage.sync.set({ settings });
        this.toggleSettings();
        this.showMessage('设置已保存');
    }

    async loadSettings() {
        const result = await chrome.storage.sync.get('settings');
        const settings = result.settings || {};
        
        document.getElementById('apiKey').value = settings.apiKey || '';
        document.getElementById('modelSelect').value = settings.model || 'moonshot-v1-8k';
        document.getElementById('maxTokens').value = settings.maxTokens || 1000;
        document.getElementById('autoSummarizeSwitch').checked = settings.autoSummarize || false;
    }

    async getSettings() {
        const result = await chrome.storage.sync.get('settings');
        return result.settings || {};
    }

    async autoSummarizeIfEnabled() {
        const settings = await this.getSettings();
        if (settings.autoSummarize) {
            this.lastSummarizedUrl = location.href;
            this.summarizeCurrentPage();
        }
    }

    async saveToHistory(summary) {
        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
        
        const historyItem = {
            url: tab.url,
            title: tab.title,
            summary: summary,
            timestamp: new Date().toISOString()
        };

        const result = await chrome.storage.local.get('history');
        const history = result.history || [];
        
        // 限制历史记录数量
        history.unshift(historyItem);
        if (history.length > 50) {
            history.splice(50);
        }

        await chrome.storage.local.set({ history });
    }

    async loadHistory() {
        const result = await chrome.storage.local.get('history');
        const history = result.history || [];
        
        const historyList = document.getElementById('historyList');
        historyList.innerHTML = '';

        if (history.length === 0) {
            historyList.innerHTML = '<div style="text-align: center; color: #999; padding: 20px;">暂无历史记录</div>';
            return;
        }

        history.forEach((item, index) => {
            const historyItem = document.createElement('div');
            historyItem.className = 'history-item';
            historyItem.innerHTML = `
                <div class="history-item-title">${item.title}</div>
                <div class="history-item-date">${new Date(item.timestamp).toLocaleString()}</div>
            `;
            
            historyItem.addEventListener('click', () => {
                this.loadHistoryItem(item);
            });
            
            historyList.appendChild(historyItem);
        });
    }

    loadHistoryItem(item) {
        this.displayResult(item.summary);
        this.toggleHistory();
    }

    async clearHistory() {
        await chrome.storage.local.remove('history');
        this.loadHistory();
        this.showMessage('历史记录已清空');
    }

    copySummary() {
        if (!this.currentResult) return;

        const text = `💡 一句话总结：\n${this.currentResult.mainContent}\n\n🔑 关键要点：\n${this.currentResult.keyPoints.map(point => `• ${point}`).join('\n')}`;
        
        navigator.clipboard.writeText(text).then(() => {
            this.showMessage('总结已复制到剪贴板');
        }).catch(() => {
            this.showError('复制失败');
        });
    }

    async saveSummary() {
        if (!this.currentResult) return;

        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
        
        const summaryData = {
            url: tab.url,
            title: tab.title,
            summary: this.currentResult,
            timestamp: new Date().toISOString()
        };

        const result = await chrome.storage.local.get('savedSummaries');
        const savedSummaries = result.savedSummaries || [];
        savedSummaries.unshift(summaryData);
        
        await chrome.storage.local.set({ savedSummaries });
        this.showMessage('总结已保存');
    }

    showMessage(message) {
        // 简单的消息提示
        const messageDiv = document.createElement('div');
        messageDiv.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: #28a745;
            color: white;
            padding: 8px 16px;
            border-radius: 4px;
            font-size: 12px;
            z-index: 1000;
        `;
        messageDiv.textContent = message;
        
        document.body.appendChild(messageDiv);
        
        setTimeout(() => {
            document.body.removeChild(messageDiv);
        }, 3000);
    }

    showError(message) {
        const messageDiv = document.createElement('div');
        messageDiv.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: #dc3545;
            color: white;
            padding: 8px 16px;
            border-radius: 4px;
            font-size: 12px;
            z-index: 1000;
        `;
        messageDiv.textContent = message;
        
        document.body.appendChild(messageDiv);
        
        setTimeout(() => {
            document.body.removeChild(messageDiv);
        }, 5000);
    }

    listenForPageUrlChange() {
        chrome.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
            if (message.action === 'pageUrlChanged') {
                const settings = await this.getSettings();
                if (settings.autoSummarize && message.url !== this.lastSummarizedUrl) {
                    this.lastSummarizedUrl = message.url;
                    this.summarizeCurrentPage();
                }
            }
        });
    }

    setupPortListener() {
        this.sidepanelPort = chrome.runtime.connect({ name: 'sidepanel' });
        this.sidepanelPort.onMessage.addListener(async (message) => {
            if (message.action === 'pageUrlChanged') {
                const settings = await this.getSettings();
                // 只在当前tab的侧边栏自动总结
                chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
                    if (tabs && tabs[0] && message.tabId === tabs[0].id) {
                        if (settings.autoSummarize && message.url !== this.lastSummarizedUrl) {
                            this.lastSummarizedUrl = message.url;
                            this.summarizeCurrentPage();
                        }
                    }
                });
            }
        });
    }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    const summarizer = new WebPageSummarizer();
    summarizer.autoSummarizeIfEnabled();
});